import org.junit.jupiter.api.Test;

import java.nio.ByteBuffer;

/**
 * @author zhu_shuai
 * @since 2021/6/1
 */
public class Demo1Buffer {
    @Test
    void test1() {
        // 缓冲区 ， 八个基本类型，除boolean外，都有缓冲区
        // 1. 设置缓冲区大小
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        System.out.println("-------------------------allocate----------------------------------");
        // 位置
        System.out.println(byteBuffer.position());
        // 界限
        System.out.println(byteBuffer.limit());
        // 容量
        System.out.println(byteBuffer.capacity());

        // 2. put() 存入缓冲区
        byteBuffer.put("abc".getBytes());
        System.out.println("-------------------------put----------------------------------");
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());

        // 3. flip() 切换为读数据模式
        byteBuffer.flip();
        System.out.println("-------------------------flip----------------------------------");
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());

        // 4. get() 读取缓冲区数据
        byte[] dst = new byte[byteBuffer.limit()];
        byteBuffer.get(dst);
        System.out.println("-------------------------get----------------------------------");
        System.out.println(new String(dst));
        System.out.println(byteBuffer.position());
        System.out.println(byteBuffer.limit());
        System.out.println(byteBuffer.capacity());

        // 5. rewind 重复读
        byteBuffer.rewind();

        // 6. clear() 清空缓冲区，但是数据依然存在，处于“被遗忘”状态
        byteBuffer.clear();

    }
}
